from quart import Blueprint, request, jsonify
import asyncio
import json
from cozepy import COZE_CN_BASE_URL, Coze, TokenAuth
from src.service.works_service import WorksService

# 创建蓝图
main_route = Blueprint('main_route', __name__)

# 扣子API配置
coze_api_token = 'pat_Bxhs0AHKId8TYxGx1tKSyFv7jEiX9qHfpktvDf9BCKcvoXUUxcBFxOzuXDyz1RDq'
coze_api_base = COZE_CN_BASE_URL
workflow_id = '7511554911194087433'

# 初始化Coze客户端
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

@main_route.route('/api/coze/workflow', methods=['POST'])
async def call_coze_workflow():
    """
    调用扣子工作流API接口
    接收URL参数，返回抖音视频数据
    """
    try:
        # 获取请求数据
        data = await request.get_json()
        
        # 验证参数
        if not data or 'url' not in data:
            return jsonify({
                'code': 400,
                'msg': 'Missing required parameter: url',
                'data': None
            }), 400
        
        url = data['url']
        
        # 验证URL格式
        if not url or not isinstance(url, str):
            return jsonify({
                'code': 400,
                'msg': 'Invalid URL parameter',
                'data': None
            }), 400
        
        # 调用扣子工作流
        workflow = coze.workflows.runs.create(
            workflow_id=workflow_id,
            parameters={
                'dy_share_url': url
            }
        )
        
        # 处理响应数据
        if workflow and workflow.data:
            
            # 存储数据到数据库
            try:
                works_service = WorksService()
                # 构造完整的响应格式，因为workflow.data是JSON字符串
                full_response = {
                    "code": 0,
                    "data": workflow.data,
                    "msg": "Success"
                }
                # 将完整响应转换为JSON字符串传递给解析器
                response_json = json.dumps(full_response)
                saved_work = await works_service.save_douyin_work(response_json, url)
                print(f"数据存储成功: {saved_work}")
            except Exception as storage_error:
                print(f"数据存储失败: {str(storage_error)}")
                # 存储失败不影响API响应
            
            return jsonify({
                'code': 0,
                'msg': 'Success',
                'data': workflow.data
            })
        else:
            return jsonify({
                'code': 500,
                'msg': 'Workflow execution failed',
                'data': None
            }), 500
            
    except Exception as e:
        # 错误处理
        return jsonify({
            'code': 500,
            'msg': f'Internal server error: {str(e)}',
            'data': None
        }), 500

@main_route.route('/api/coze/test', methods=['GET'])
async def test_coze_workflow():
    """
    测试接口，使用预设的测试URL
    """
    test_url = 'https://www.douyin.com/user/MS4wLjABAAAAyiUBvOEjnzVYHl3xyIopxDpk1e7ECR-TW10I14EdS80?from_tab_name=main&modal_id=7541687869727870262'
    
    try:
        # 调用扣子工作流
        workflow = coze.workflows.runs.create(
            workflow_id=workflow_id
        )
        
        # 处理响应数据
        if workflow and workflow.data:
            return jsonify({
                'code': 0,
                'msg': 'Test Success',
                'data': workflow.data,
                'test_url': test_url
            })
        else:
            return jsonify({
                'code': 500,
                'msg': 'Test workflow execution failed',
                'data': None
            }), 500
            
    except Exception as e:
        # 错误处理
        return jsonify({
            'code': 500,
            'msg': f'Test error: {str(e)}',
            'data': None
        }), 500